window.onload = function () {
  fetchActivities();  // 页面加载时获取活动数据
};

const logoutBtn = document.getElementById("logout-btn");
let currentActivityId = null; // 当前操作的活动ID，新增时为null

// 获取活动数据
function fetchActivities() {
  fetch('http://localhost:8083/api/admin/activity/list', {  // 这里是后端活动列表接口的 URL
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      pageNum: 1,  // 当前页码
      pageSize: 10  // 每页数据量
    })
  })
  .then(response => response.json())
  .then(data => {
    if (data.code === 200) {
      renderActivities(data.data.records);  // 假设后端返回的数据结构为：data.data.records
    } else {
      alert('获取活动数据失败');
    }
  })
  .catch(error => {
    console.error('Error fetching activities:', error);
    alert('获取活动数据失败');
  });
}

// 渲染活动数据到表格
function renderActivities(activities) {
  const tableBody = document.getElementById("activityTableBody");
  tableBody.innerHTML = '';  // 清空表格内容
  activities.forEach(activity => {
    const row = document.createElement("tr");
    row.id = `activity-${activity.id}`; // 给每行一个唯一ID
    row.innerHTML = `
      <td>${activity.id}</td>
      <td>${activity.name}</td>
      <td>${activity.category}</td>
      <td>${activity.title}</td>
      <td>${activity.creator}</td>
      <td class="status">${activity.status === 1 ? '进行中' : '已结束'}</td>
      <td>${activity.startTime}</td>
      <td>${activity.endTime}</td>
      <td>
        <button onclick="editActivity(${activity.id})">编辑</button>
        <button onclick="toggleStatus(${activity.id}, ${activity.status})">${activity.status === 1 ? '关闭' : '打开'}</button>
        <button onclick="deleteActivity(${activity.id})">删除</button>
      </td>
    `;
    tableBody.appendChild(row);
  });
}

// 打开弹窗
function openModal(action, activityId = null) {
  const modal = document.getElementById("data-modal");
  const modalTitle = document.getElementById("modal-title");
  const saveBtn = document.getElementById("save-data-btn");

  if (action === 'create') {
    modalTitle.textContent = "新增活动";
    saveBtn.textContent = "保存";
    currentActivityId = null;
    clearModalFields();
  } else if (action === 'edit') {
    modalTitle.textContent = "编辑活动";
    saveBtn.textContent = "保存修改";
    currentActivityId = activityId;

    // 获取活动数据并填充到输入框中
    fetch(`http://localhost:8083/api/admin/activity/${activityId}`)
      .then(response => response.json())
      .then(data => {
        if (data.code === 200) {
          const activity = data.data;
          document.getElementById("name").value = activity.name;
          document.getElementById("category").value = activity.category;
          document.getElementById("title").value = activity.title;
          document.getElementById("creator").value = activity.creator;
          document.getElementById("start_time").value = activity.startTime;
          document.getElementById("end_time").value = activity.endTime;
        } else {
          alert('获取活动数据失败');
        }
      })
      .catch(error => {
        console.error('Error fetching activity:', error);
        alert('获取活动数据失败');
      });
  }

  modal.style.display = "block"; // 打开弹窗
}

// 清空弹窗中的输入字段
function clearModalFields() {
  document.getElementById("name").value = "";
  document.getElementById("category").value = "";
  document.getElementById("title").value = "";
  document.getElementById("creator").value = "";
  document.getElementById("start_time").value = "";
  document.getElementById("end_time").value = "";
}

// 关闭弹窗
function closeModal() {
  const modal = document.getElementById("data-modal");
  modal.style.display = "none";
}

// 监听取消按钮，点击时关闭弹窗
document.getElementById("cancel-btn").addEventListener("click", closeModal);
// 监听关闭按钮，点击时关闭弹窗
document.getElementById("close-modal").addEventListener("click", closeModal);

// 保存数据
document.getElementById("data-form").addEventListener("submit", function (event) {
  event.preventDefault();

  const name = document.getElementById("name").value.trim();
  const category = document.getElementById("category").value.trim();
  const title = document.getElementById("title").value.trim();
  const creator = document.getElementById("creator").value.trim();
  const start_time = document.getElementById("start_time").value.trim();
  const end_time = document.getElementById("end_time").value.trim();

  if (name === "" || category === "" || title === "" || creator === "" || start_time === "" || end_time === "") {
    alert("请输入所有活动信息");
    return;
  }

  const activityDTO = {
    name,
    category,
    title,
    creator,
    startTime: start_time,
    endTime: end_time
  };

  if (currentActivityId === null) {
    // 新增活动
    fetch('http://localhost:8083/api/admin/activity/add', {  // 新增活动接口
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(activityDTO)
    })
    .then(response => response.json())
    .then(data => {
      if (data.code === 200) {
        fetchActivities();  // 重新获取活动列表
        closeModal();
      } else {
        alert('新增活动失败');
      }
    })
    .catch(error => {
      console.error('Error adding activity:', error);
      alert('新增活动失败');
    });
  } else {
    // 编辑活动
    activityDTO.id = currentActivityId;
    fetch('http://localhost:8083/api/admin/activity/update', {  // 编辑活动接口
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(activityDTO)
    })
    .then(response => response.json())
    .then(data => {
      if (data.code === 200) {
        fetchActivities();  // 重新获取活动列表
        closeModal();
      } else {
        alert('编辑活动失败');
      }
    })
    .catch(error => {
      console.error('Error editing activity:', error);
      alert('编辑活动失败');
    });
  }
});

// 编辑活动
function editActivity(id) {
  openModal('edit', id);
}

// 删除活动
function deleteActivity(id) {
  fetch(`http://localhost:8083/api/admin/activity/delete/${id}`, {  // 删除活动接口
    method: 'POST',
  })
  .then(response => response.json())
  .then(data => {
    if (data.code === 200) {
      fetchActivities();  // 重新获取活动列表
    } else {
      alert('删除活动失败');
    }
  })
  .catch(error => {
    console.error('Error deleting activity:', error);
    alert('删除活动失败');
  });
}

// 切换活动状态
function toggleStatus(id, currentStatus) {
  const newStatus = currentStatus === 1 ? 0 : 1;  // 1代表进行中，0代表已结束
  fetch(`http://localhost:8083/api/admin/activity/status/${id}?status=${newStatus}`, {  // 更新活动状态接口
    method: 'POST',
  })
  .then(response => response.json())
  .then(data => {
    if (data.code === 200) {
      fetchActivities();  // 重新获取活动列表
    } else {
      alert('更新活动状态失败');
    }
  })
  .catch(error => {
    console.error('Error updating activity status:', error);
    alert('更新活动状态失败');
  });
}

// 退出按钮点击事件
logoutBtn.addEventListener('click', () => {
  window.location.href = '../login.html'; // 假设你要跳转到登录页面
});
